package com.wd.live.viewmodel

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.wd.live.BaseConstant
import com.wd.live.tool.LocalData
import com.wd.live.tool.socket.WebSocketUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MultipartBody
import org.json.JSONObject
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


class OpenLiveViewModel : BaseViewModel() {
    private var webSocketUtils: WebSocketUtils? = null

    val liveData: MutableLiveData<LocalData.LiveInfo> by lazy {
        MutableLiveData<LocalData.LiveInfo>()
    }

    /**
     * 送礼的礼物名称
     */
    val giftName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    /**
     * 连麦同意
     */
    val agreeLink: MutableLiveData<LocalData.Link> by lazy {
        MutableLiveData<LocalData.Link>()
    }

    val payMsg: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    val lookLiveData: MutableLiveData<LocalData.LookLiveInfo> by lazy {
        MutableLiveData<LocalData.LookLiveInfo>()
    }

    val requestLink: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    val giftInfo: MutableLiveData<MutableList<LocalData.GiftInfo>> by lazy {
        MutableLiveData<MutableList<LocalData.GiftInfo>>()
    }

    fun openLive(type: Int, title: String, image: MultipartBody.Part?, lat: Double?, lng: Double?) {
        val params = HashMap<String, Any?>()
        params["liveType"] = type
        params["liveTitle"] = title
        params["longitude"] = lng ?: 116.40400
        params["latitude"] = lat ?: 39.92800
        systemApi?.openLive(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params, image)
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        if (bean.status == "1003") {
                            Log.d("provideSystemApi", bean.message.toString())
                        } else {
                            liveData.value = bean.liveData
                        }
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }
    }

    fun startPushStream(liveId: Int) {
        val params = HashMap<String, Any?>()
        params["liveId"] = liveId
        systemApi?.pushLive(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params)?.let {
            it.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ bean ->
                    Log.d("provideSystemApi", bean.toString())
                }, { error ->
                    Log.d("provideSystemApi", error.message.toString())
                })
        }
    }

    fun closeLive() {
//        systemApi?.closeLive( 378, "1692752817851378")
        systemApi?.closeLive(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "")
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        Log.d("provideSystemApi", bean.toString())
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }
    }

    fun lookLive(liveId: Int?) {
        val params = HashMap<String, Any?>()
        params["liveId"] = liveId
        systemApi?.lookLive(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params)?.let {
            it.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ bean ->
                    lookLiveData.value = bean.result
                    Log.d("provideSystemApi", bean.toString())
                }, { error ->
                    Log.d("provideSystemApi", error.message.toString())
                })
        }
    }

    fun requestLink(liveId: Int) {
        val params = HashMap<String, Any?>()
        params["liveId"] = liveId
        systemApi?.requestLink(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params)
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        if (bean.status == "0000") {
                            requestLink.value = "连麦申请成功，等待"
                        } else {
                            requestLink.value = bean.message
                        }
                        Log.d("provideSystemApi", bean.toString())
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }

    }

    fun getGiftList() {
        systemApi?.getGiftList(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "")
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        if (bean.status == "0000") {
                            giftInfo.value = bean.result
                        }
                        Log.d("provideSystemApi", bean.toString())
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }
    }

    fun sendGift(data: LocalData.GiftInfo, liveId: Int?) {
        val params = HashMap<String, Any?>()
        params["giftId"] = data.giftId
        params["liveId"] = liveId
        systemApi?.sendGift(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params)
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        if (bean.status == "0000") {
                        }
                        Log.d("provideSystemApi", bean.toString())
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }
    }

    /**
     * 充值
     */
    fun recharge() {
        val params = HashMap<String, Any?>()
        params["money"] = 5000
        params["payType"] = 2
        params["sign"] = MD5("bw${BaseConstant.userId}2live")?.uppercase()
        systemApi?.recharge(BaseConstant.userId ?: 0, BaseConstant.sessionId ?: "", params)
            ?.let {
                it.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ bean ->
                        if (bean.status == "0000") {
                            payMsg.postValue(bean.result)
                        }
                        Log.d("provideSystemApi", bean.toString())
                    }, { error ->
                        Log.d("provideSystemApi", error.message.toString())
                    })
            }
    }

    fun MD5(sourceStr: String): String? {
        var result = ""
        try {
            val md = MessageDigest.getInstance("MD5")
            md.update(sourceStr.toByteArray())
            val b = md.digest()
            var i: Int
            val buf = StringBuffer("")
            for (offset in b.indices) {
                i = b[offset].toInt()
                if (i < 0) i += 256
                if (i < 16) buf.append("0")
                buf.append(Integer.toHexString(i))
            }
            result = buf.toString()
        } catch (e: NoSuchAlgorithmException) {
            println(e)
        }
        return result
    }

    fun connectSocket(compositeWsUrl: String, context: Context) {

        //开启ws连接
        webSocketUtils = WebSocketUtils().startConnect(compositeWsUrl, context)
        //消息监听
        webSocketUtils?.setOnMessageListener(object : WebSocketUtils.OnMessageListener {

            override fun message(msg: String?) {

                Log.d("connectSocket msg", msg.toString())
                val socketBean = Gson().fromJson(msg, LocalData.WebSocketInfo::class.java)
                when (socketBean.msgType) {
                    101 -> {
                        //获取type 101=评论文本 102=进房间 103=送礼
                        when (JSONObject(msg.toString()).getInt("type")) {
                            103 -> {
                                //送礼礼物名称
                                giftName.value = "火箭"
                            }
                        }
                    }
                    //直播间实时人数更新消息
                    102 -> {

                    }
                    //鹊桥类消息
                    103 -> {
                        val bridge = Gson().fromJson(msg, LocalData.Bridge::class.java)
                        when (bridge.status) {
                            101 -> {}
                            102 -> {}
                            103 -> {}
                        }
                    }
                    //连麦类消息
                    104 -> {
                        val link = Gson().fromJson(msg, LocalData.Link::class.java)
                        //同意后，打开本地数据流,使用当前看播用户的userId
                        agreeLink.value = link
                    }
                }
            }
        })
    }

    fun closeWebSocket() {
        webSocketUtils?.closeConnect()
    }

}
